package kr.co.happenstance;

import java.util.ArrayList;

import kr.co.happenstance.lib.MatchingLib;
import kr.co.happenstance.lib.MemberLib;
import kr.co.happenstance.lib.vo.LibResultVo;
import kr.co.happenstance.lib.vo.RequestCountResultVo;
import kr.co.happenstance.util.AndroidUtil;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 어플리케이션 Activity에서 상속 해야 하는 기본 Activity 클래스<br>
 * 
 * 구글맵을 사용하기 위해 FragmentActivity를 상속 받음
 *  
 * @author Administrator
 *
 */
@SuppressWarnings("unused")
public class BaseActivity extends FragmentActivity implements LocationListener{
	protected final String _TAG_ = "<<<BaseActivity>>>";
	
	/**
	 * 현재 Activity
	 */
	protected Activity currActivity;
	
	/**
	 * init 메소드 호출 여부<br><br>
	 * 
	 * 요청 카운트를 서버에 질의 여부를 판단하기 위한 변수
	 * 
	 * init 메소드를 호출한 Activiy에서만 질의함
	 * 
	 */
	protected boolean isInitInvoke;
	
	/**
	 * 팝업 Dialog 객체
	 */
	protected Dialog popupDialog;	
	
	/**
	 * 
	 */
	protected String gpsProvider;
	
	/**
	 * LocationManager 객체
	 */
	protected LocationManager locationManager;
	
	/**
	 * 현재 내위치 정보를 갖고 있는 Location 객체 
	 */
	protected Location myLocation = null;
	
	/**
	 * GPS 사용 가능 여부
	 */
	protected boolean isAbleGps = false;
	
	/**
	 * 생성된 모든 Activity 리스트
	 */
	protected static ArrayList<Activity> activityList  = new ArrayList<Activity>();
	
	/**
	 * ProgressDialog 객체
	 */
	protected CustomProgressDialog progressDlg;	
	
	/**
	 * Application 객체
	 */
	protected MyApplication myApp;
	
	/**
	 * Activity 타이틀 ImageView 객체
	 */
	protected ImageView ivTitle = null;	
	
	/**
	 * 리로드 ImageButton 객체
	 */
	protected ImageView btnReload = null;
	
	/**
	 * 뺏지 카운트 TextView 객체
	 */
	protected TextView tvBadgeCount = null;
	
	/**
	 * 메뉴 - 만나자 ImageButton 객체
	 */
	protected ImageButton menuMeet = null;

	/**
	 * 메뉴 - 홈 ImageButton 객체
	 */
	protected ImageButton menuHome = null;
	
	/**
	 * 메뉴 - 요청리스트 ImageButton 객체
	 */
	protected ImageButton menuReqlist = null;
	
	/**
	 * 메뉴 - 설정 ImageButton 객체
	 */
	protected ImageButton menuSetting = null;
	
	/**
	 * 메뉴 OnClickListener 객체
	 */
	protected OnClickListener menuOnClickListener;		
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		progressDlg = new CustomProgressDialog(this);
		myApp = (MyApplication) this.getApplication();
	
		menuOnClickListener = new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = null;
				switch(v.getId()){
					case R.id.menu_meet:
						/*
						intent = new Intent(BaseActivity.this, MeetActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);	
						*/
						showMeetDialog();
						break;
					case R.id.menu_home:
						intent = new Intent(BaseActivity.this, HomeActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);						
						break;
						
					case R.id.menu_reqlist:
						intent = new Intent(BaseActivity.this, RequestListActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);								
						break;
						
					case R.id.menu_setting:
						intent = new Intent(BaseActivity.this, SettingActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
						break;
				}
			}
			
		};
		
		//LocationListener 핸들
		locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		
		
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);    
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		criteria.setAltitudeRequired(false); 
		criteria.setBearingRequired(false);
		criteria.setSpeedRequired(false);  
		criteria.setCostAllowed(false); 
		
		//로케이션 메니저의 provider
		gpsProvider = locationManager.getBestProvider(criteria, true);  
		Log.d(_TAG_,"provider["+gpsProvider+"]");
		
		if(gpsProvider != null){
			myLocation = locationManager.getLastKnownLocation(gpsProvider);
			locationManager.requestLocationUpdates(gpsProvider, 300, 1, this);
			
			if(myLocation == null){
				if(gpsProvider.equals(LocationManager.GPS_PROVIDER)){
					myLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
					locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 300, 1, this);
					
				}else{
					myLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
					locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300, 1, this);
				}
			}
			
		}
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		this.overridePendingTransition(0, 0);
		
		//네트웍 체크
		if(!AndroidUtil.isNetworkConnectionAvailable(this)){
			new CustomAlertDialogBuilder(this)
			.setTitle(this.getString(R.string.alert_title))
			.setMessage(getString(R.string.alert_msg_network_disable))
			.setCancelable(true)
			.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int arg1) {
					dialog.dismiss();
					
					//전체 Activity 종료
					appFinish();				
					
				}
			})
			.create();				
		}
		
		//GPS 체크
		if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
			new CustomAlertDialogBuilder(this)
			.setTitle(R.string.alert_title_gps)
			.setMessage(R.string.alert_msg_gps)
			.setCancelable(true)
			.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int arg1) {
					dialog.dismiss();
					
					//GPS 설정 호출
					Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
					intent.addCategory(Intent.CATEGORY_DEFAULT); 
					startActivity(intent);
				}
			})
			.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			})
			.create();				
		}
		

		if(this.currActivity != null && isInitInvoke){
			new RequestCountTask().execute();
		}
		
	}	
	
	
	@Override
	protected void onDestroy(){
		super.onDestroy();
	}	
	
	/**
	 * 상속받은 Activity 초기화 메소드<br><br>
	 * 
	 * 이메소드 호출전에 UI xml에서 include_top, include_bottom 을 inclucde 해야함
	 * 
	 * @param currActivity
	 * @param menuId
	 */
	protected void init(Activity currActivity, final int menuId){	
		isInitInvoke =  true;
		addActivity(currActivity);
		
		//include_top
		ivTitle = (ImageView) currActivity.findViewById(R.id.iv_title);
		btnReload = (ImageButton) currActivity.findViewById(R.id.btn_reload);
		
		//include_bottom
		this.menuMeet =  (ImageButton) currActivity.findViewById(R.id.menu_meet);
		this.menuHome =  (ImageButton) currActivity.findViewById(R.id.menu_home);
		this.menuReqlist =  (ImageButton) currActivity.findViewById(R.id.menu_reqlist);
		this.menuSetting =  (ImageButton) currActivity.findViewById(R.id.menu_setting);
		this.tvBadgeCount = (TextView) currActivity.findViewById(R.id.tv_badge_count);
		
		this.menuMeet.setOnClickListener(menuOnClickListener);
		this.menuHome.setOnClickListener(menuOnClickListener);
		this.menuReqlist.setOnClickListener(menuOnClickListener);
		this.menuSetting.setOnClickListener(menuOnClickListener);
		
		//현재 메뉴 타이틀 셋팅및 선택 메뉴 Background 교체
		switch(menuId){
			case C.MENU_ID_MEET:
				ivTitle.setImageResource(R.drawable.title_menu_meet);
				
				//모든 메뉴 클릭 비활성
				menuMeet.setBackgroundResource(R.drawable.menu_meet_over);
				menuHome.setBackgroundResource(R.drawable.menu_home);
				menuReqlist.setBackgroundResource(R.drawable.menu_reqlist);
				menuSetting.setBackgroundResource(R.drawable.menu_setting);
				
				//모든 메뉴 클릭 리스너 해제
				menuMeet.setOnClickListener(null);
				menuHome.setOnClickListener(null);
				menuReqlist.setOnClickListener(null);
				menuSetting.setOnClickListener(null);
				
				break;
			case C.MENU_ID_HOME:
				ivTitle.setImageResource(R.drawable.title_menu_home);
				menuHome.setBackgroundResource(R.drawable.menu_home_over);
				menuHome.setOnClickListener(null);
				break;
			case C.MENU_ID_REQLIST:
				ivTitle.setImageResource(R.drawable.title_menu_request_list);
				menuReqlist.setBackgroundResource(R.drawable.menu_reqlist_over);
				menuReqlist.setOnClickListener(null);
				btnReload.setVisibility(View.VISIBLE);
				break;
			case C.MENU_ID_SETTING:
				ivTitle.setImageResource(R.drawable.title_menu_setting);
				menuSetting.setBackgroundResource(R.drawable.menu_setting_over);
				menuSetting.setOnClickListener(null);
				break;
			case C.MENU_ID_PUSH_MEET:
				ivTitle.setImageResource(R.drawable.title_menu_meet);
				break;
			case C.MENU_ID_RECIPIENT_WAITING:
				ivTitle.setImageResource(R.drawable.title_menu_waiting);
				
				//모든 메뉴 클릭 비활성
				menuMeet.setBackgroundResource(R.drawable.menu_meet);
				menuHome.setBackgroundResource(R.drawable.menu_home);
				menuReqlist.setBackgroundResource(R.drawable.menu_reqlist);
				menuSetting.setBackgroundResource(R.drawable.menu_setting);
				
				//모든 메뉴 클릭 리스너 해제				
				menuMeet.setOnClickListener(null);
				menuHome.setOnClickListener(null);
				menuReqlist.setOnClickListener(null);
				menuSetting.setOnClickListener(null);				
				
				break;
			case C.MENU_ID_RECIPIENT_LIST:
				ivTitle.setImageResource(R.drawable.title_menu_recipient_list);
				btnReload.setVisibility(View.VISIBLE);
				
				//모든 메뉴 클릭 비활성
				menuMeet.setBackgroundResource(R.drawable.menu_meet);
				menuHome.setBackgroundResource(R.drawable.menu_home);
				menuReqlist.setBackgroundResource(R.drawable.menu_reqlist);
				menuSetting.setBackgroundResource(R.drawable.menu_setting);
				
				//모든 메뉴 클릭 리스너 해제				
				menuMeet.setOnClickListener(null);
				menuHome.setOnClickListener(null);
				menuReqlist.setOnClickListener(null);
				menuSetting.setOnClickListener(null);
				
				break;
			case C.MENU_ID_REQUESTOR_WAITING:
				ivTitle.setImageResource(R.drawable.title_menu_waiting);
				
				//모든 메뉴 클릭 비활성
				menuMeet.setBackgroundResource(R.drawable.menu_meet);
				menuHome.setBackgroundResource(R.drawable.menu_home);
				menuReqlist.setBackgroundResource(R.drawable.menu_reqlist);
				menuSetting.setBackgroundResource(R.drawable.menu_setting);
				
				//모든 메뉴 클릭 리스너 해제				
				menuMeet.setOnClickListener(null);
				menuHome.setOnClickListener(null);
				menuReqlist.setOnClickListener(null);
				menuSetting.setOnClickListener(null);				
				
				break;
				
		}
		
		//요청 목록 badge 셋팅
		//new RequestCountTask().execute();
		
		
	}
	
	/**
	 * Activity 리스트 추가 메소드<br><br>
	 * 
	 * init 메소드를 호출하지 않는 서브 Activity에서 사용하는 Activity 등록 메소드
	 * 
	 * @param activity
	 */
	protected void addActivity(Activity activity){
		this.currActivity = activity;
		activityList.add(activity);
	}
	
	/**
	 * App 종료 메소드
	 */
	protected void appFinish(){
		for(Activity act: activityList) {
			if(act != null) act.finish();
		}
	}
	
	/**
	 * 프로그래스바(로딩바) 보여주는 메소드
	 * 
	 * @param isCancelable		취소가능 여부
	 */
	protected void showProgress(boolean isCancelable){
		try{
			progressDlg.setCancelable(isCancelable);
			progressDlg.show();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 프로그래스바(로딩바) 보여주는 메소드 - 오버라이딩<br><br>
	 * 
	 * 취소 불가능한 프로그래스바 
	 */
	protected void showProgress(){
		showProgress(false);
	}	
	
	/**
	 * 프로그래스바(로딩바) 닫기 메소드
	 */
	protected void closeProgress() {
		try{
	    	if (progressDlg.isShowing())
	    		progressDlg.dismiss();
		}catch(Exception e){};
	}
	
	/**
	 * 프로그래스바 메세지 셋팅 메소드
	 * 
	 * @param msg
	 */
	protected void setProgressMsg(String msg){
		progressDlg.setMessage(msg);
	}
	
	/**
	 * 프로그래스바 메세지 세팅 메소드
	 * 
	 * @param resId
	 */
	protected void setProgressMsg(int resId){
		progressDlg.setMessage(resId);
	}

	/**
	 * 우리지금 만나 메뉴 진입시 프로필 전송을 물어보는 Dialog 호출 메소드 
	 */
	protected void showMeetDialog(){
		LayoutInflater inflater = (LayoutInflater) this.getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.popup_meet, (ViewGroup) this.findViewById(R.id.rl_popup));
		
		//리스너 등록
		ImageButton btnClose = (ImageButton) layout.findViewById(R.id.btn_pop_close);
		ImageButton btnOk = (ImageButton) layout.findViewById(R.id.btn_pop_ok);
		ImageButton btnCancel = (ImageButton) layout.findViewById(R.id.btn_pop_cancel);
		final CheckBox chkPopProfile =  (CheckBox) layout.findViewById(R.id.chk_pop_profile);
		
		View.OnClickListener listener = new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				popupDialog.dismiss();
				switch(v.getId()){
					case R.id.btn_pop_ok:
						Intent intent = new Intent(BaseActivity.this, MeetActivity.class);
						intent.putExtra("profileYN", chkPopProfile.isChecked()?"Y":"N");
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
						break;
				}
			}
		};
		
		btnClose.setOnClickListener(listener);
		btnOk.setOnClickListener(listener);
		btnCancel.setOnClickListener(listener);
		
		popupDialog = AndroidUtil.getPopupDialog(this, layout, false);
		popupDialog.show();				
	}
	
	@Override
	public void onLocationChanged(Location location) {
		
		
		try{
			float distance = location.distanceTo(myLocation);
			//Log.d(_TAG_, "distance["+distance+"]");
			//Toast.makeText(this, "["+distance+"]", Toast.LENGTH_SHORT).show();
			
			if(distance > 10.0){
				myLocation = location;
				new MemberLocationUpdateTask().execute();
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
	}	
	
	protected class MemberLocationUpdateTask extends AsyncTask<Void, Void, LibResultVo> {
		@Override
		protected LibResultVo doInBackground(Void... arg0) {
			try{
				new MemberLib().memberLocationUpdate(myApp.id, Double.toString(myLocation.getLatitude()), Double.toString(myLocation.getLongitude()));
			}catch(Exception e){
				e.printStackTrace();
			}
			return null;
		}
		
	}
	
	protected class RequestCountTask extends AsyncTask<Void, Void, LibResultVo> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showProgress();
		}	
		
		@Override
		protected LibResultVo doInBackground(Void... arg0) {
			LibResultVo vo = null;
			try{
				MatchingLib lib = new MatchingLib();
				vo = lib.requestCount(myApp.id);
			}catch(Exception e){
				e.printStackTrace();
			}
			return vo;
		}
		
		@Override
		protected void onPostExecute(LibResultVo resultVo) {
			closeProgress();
			RequestCountResultVo vo = (RequestCountResultVo) resultVo;
			if(vo != null){
				if(vo.getRequestCount()>0){
					int requestCount = vo.getRequestCount();
					if(requestCount > 99) requestCount = 99;
					
					tvBadgeCount.setText(Integer.toString(requestCount));
					tvBadgeCount.setVisibility(View.VISIBLE);
				}
			}
			
		}	
		
	}	
	
}
